package com.wm.web.action;

import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.wm.bean.User;
import com.wm.comm.Constant;
import com.wm.comm.MD5;
import com.wm.service.UserService;
import com.wm.web.servlet.*;

public class RegUser extends BaseAction implements SessionAware {
	private static final Log logger = LogFactory.getLog(RegUser.class);
	
	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	private Map session;

	public void setSession(Map session) {
		this.session = session;
	}

	public Map getSession() {
		return session;
	}
	
	private String username;
	private String password;
	private String email;
	private String verifycode;
	private String error;
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}
	
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String getVerifycode() {
		return verifycode;
	}

	public void setVerifycode(String verifycode) {
		this.verifycode = verifycode;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}
	
	public String execute() {
		try {
			return this.executeMethod(this.getAction());
		} catch (Exception e) {
			logger.error(e);
			return INPUT;
		}
	}

	/**
	 * 初始页
	 */
	public String index(){
		this.setAction("index");
		return "index";
	}
	
	/**
	 * 注册
	 */
	public String save(){
		//验证码正确
		if(!getSessionAuthCode().equalsIgnoreCase(verifycode)){
			this.addFieldError("error", this.getText("error.autherror"));
			this.setError("1");
			return "index";
		}
		
		if(this.getUsername()==null ||this.getUsername().trim().equals("")||this.getUsername().length()>30){
			this.addFieldError("error", this.getText("error.username"));
			this.setError("1");
			return "index";
		}
		
		if(!checkUserName(this.getUsername())){
			this.addFieldError("error", this.getText("error.username"));
			this.setError("1");
			return "index";
		}
		
		if(this.getPassword()==null ||this.getPassword().trim().equals("")||this.getPassword().length()>20){
			this.addFieldError("error", this.getText("error.password"));
			this.setError("1");
			return "index";
		}
		
		if(!checkPassword(this.getPassword())){
			this.addFieldError("error", this.getText("error.password"));
			this.setError("1");
			return "index";
		}
		
		if(this.getEmail()==null ||this.getEmail().trim().equals("")||this.getEmail().length()>50){
			this.addFieldError("error", this.getText("error.email"));
			this.setError("1");
			return "index";
		}
		
		if(!checkEmail(this.getEmail())){
			this.addFieldError("error", this.getText("error.email"));
			this.setError("1");
			return "index";
		}
		
		if(this.getUsername()!=null&&!this.getUsername().trim().equals("")){
			this.setUser(this.getUserService().findUserByUserName(this.getUsername()));
			if(this.getUser()!=null){
				this.addFieldError("error", this.getText("error.username.being"));
				this.setError("1");
				return "index";
			}
		}
		
		User u = new User();
		MD5 md5 = new MD5();
		u.setUserName(this.getUsername());
		u.setUserPwd(md5.getMD5ofStr(this.getPassword()));
		u.setUserPwdShow(this.getPassword());
		u.setUserEmail(this.getEmail());
		u.setValid(0);
		u.setIsShow(1);
		u.setEmailAddTime(new Date());
		u.setAddTime(new Date());
		this.setUser(this.getUserService().saveUser(u));
		if(this.getUser()!=null && this.getUser().getId()>0){
			UserSession us = new UserSession();
			us.setUid(this.getUser().getId());
			us.setUsername(this.getUser().getUserName());
			us.setEmail(this.getUser().getUserEmail());
			this.getSession().put(Constant.USER_SESSION_KEY,us);
			if(Constant.USER_COOKIES){
				HttpServletRequest request = ServletActionContext.getRequest();
				HttpServletResponse response = ServletActionContext.getResponse();
				UserCookie userCookie = new UserCookie(request,response);
				userCookie.addCookie(Constant.USER_COOKIE_KEY, String.valueOf(us.getUid()));
			}
			
		}
		return "index";
	} 
	
	/**
	 * 查询用户名是否存在
	 * @return
	 */
	public String checkUsername(){
		if(this.getUsername()!=null&&!this.getUsername().trim().equals("")){
			this.setUser(this.getUserService().findUserByUserName(this.getUsername()));
		}
		return "regUserAjax";
	}
	
	private String getSessionAuthCode() {
        String auth = (String) this.getSession().get("authCode");
        if(StringUtils.isBlank(auth)){
        	return "";
        }else{
        	return auth;
        }
    }
	
	public static boolean checkUserName(String userName) {
//	  String regex = "([a-z]|[A-Z]|[0-9]|[\\u4e00-\\u9fa5])+";
	  //String regex = "^[a-zA-Z0-9_]+$";
	  String regex = "^[a-zA-Z0-9_]{6,18}$";
	  Pattern p = Pattern.compile(regex);
	  Matcher m = p.matcher(userName);
	  return m.matches();
	}
	
	public static boolean checkPassword(String password) {
//	  String regex = "([a-z]|[A-Z]|[0-9]|[\\u4e00-\\u9fa5])+";
      String regex = "^[a-zA-Z0-9_]{6,18}$";
	  Pattern p = Pattern.compile(regex);
	  Matcher m = p.matcher(password);
	  return m.matches();
	}
	
	public static boolean checkEmail(String email) {
	  String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	  Pattern p = Pattern.compile(regex);
	  Matcher m = p.matcher(email);
	  return m.matches();
	}
	
	public static void main(String[] args) {
	  String regex = "^[a-zA-Z0-9_]{6,18}$";
	  Pattern p = Pattern.compile(regex);
	  Matcher m = p.matcher("sad_1");
	  System.out.println(m.matches());
	}
}
